package com.funtonow.jqdk.fkcs.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.bean.IdCardAndBankInfo;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.utils.AppUtils;
import com.funtonow.jqdk.utils.FileUtils;
import com.funtonow.jqdk.utils.GenerateSign;
import com.funtonow.jqdk.utils.GlideUtils;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.HttpUtil2;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.StringUtil;
import com.funtonow.jqdk.utils.ToastUtils;
import com.funtonow.jqdk.widget.IOSAlertDialog;
import com.funtonow.jqdk.widget.ProgressDialogUtil;
import com.megvii.meglive_sdk.listener.DetectCallback;
import com.megvii.meglive_sdk.listener.PreCallback;
import com.megvii.meglive_sdk.manager.MegLiveManager;
import com.shehuan.niv.NiceImageView;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.utils.LogUtils;
import okhttp3.Call;

import static com.funtonow.jqdk.base.UrlUtils.GET_BIZTOKEN_URL;
import static com.funtonow.jqdk.base.UrlUtils.OCR_ID_CARD;
import static com.funtonow.jqdk.base.UrlUtils.UPDATE;
import static com.funtonow.jqdk.base.UrlUtils.VERIFY_URL;

/**
 * @author Jiajien
 * @date 2019/7/12
 */
public class CardActivity extends BaseActivity implements View.OnClickListener, DetectCallback, PreCallback {

    @BindView(R.id.iv_card_back)
    ImageView ivCardBack;
    @BindView(R.id.iv_card_front)
    ImageView ivCardFront;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.ll_card_front)
    LinearLayout llCardFront;
    @BindView(R.id.ll_card_back)
    LinearLayout llCardBack;
    @BindView(R.id.ll_front_info)
    LinearLayout llFrontInfo;
    @BindView(R.id.ll_back_info)
    LinearLayout llBackInfo;
    @BindView(R.id.iv_front)
    NiceImageView ivFront;
    @BindView(R.id.iv_back)
    NiceImageView ivBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_id_card)
    TextView tvIdCard;
    @BindView(R.id.tv_issue_authority)
    TextView tvIssueAuthority;
    @BindView(R.id.tv_expiry_date)
    TextView tvExpiryDate;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.tv_user_agreement)
    TextView tvUserAgreement;


    private Intent intent;
    private MegLiveManager megLiveManager;


    private String sign = "";
    private static final String SIGN_VERSION = "hmac_sha1";

    private static final int REQUEST_CODE_CAMERA = 102;

    @Override
    public int getLayoutRes() {
        return R.layout.fk_activity_card;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        initToolbar("身份信息");
        initAccessTokenWithAkSk();
        initFaceId();
        //getBizToken("贾记恩", "410928199306052413");、
        setAgreement();
    }


    public void initFaceId() {
        megLiveManager = MegLiveManager.getInstance();
        /**
         * 如果build.gradle中的applicationId 与 manifest中package不一致，必须将manifest中package通过
         * 下面方法传入，如果一致可以不调用此方法
         */
        megLiveManager.setManifestPack(this, getApplicationInfo().packageName);
        long currtTime = System.currentTimeMillis() / 1000;
        long expireTime = (System.currentTimeMillis() + 60 * 60 * 100) / 1000;
        sign = GenerateSign.appSign(Constants.FACE_ID_API_KEY, Constants.FACE_ID_SECRET, currtTime, expireTime);
    }


    /**
     * 用明文ak，sk初始化
     */
    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();

            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                LogUtil.i("AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(), Constants.AI_APP_KEY, Constants.AI_SECRET_KEY);
    }

    @OnClick({R.id.ll_card_front, R.id.ll_card_back, R.id.fl_front, R.id.fl_back,
            R.id.iv_camera_front, R.id.iv_camera_back, R.id.btn_register})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_card_front:
            case R.id.fl_front:
            case R.id.iv_camera_front:
                intent = new Intent(this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtils.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                break;
            case R.id.ll_card_back:
            case R.id.fl_back:
            case R.id.iv_camera_back:
                intent = new Intent(this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtils.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                break;
            case R.id.btn_register:
                new IOSAlertDialog(this).builder().
                        setTitle("身份有误将影响授信结果，请确认")
                        .setMsg(tvName.getText().toString() + "\n" + tvIdCard.getText().toString())
                        .setNegativeButton("返回修改", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        })
                        .setPositiveButton("确认无误", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                getBizToken(tvName.getText().toString(), tvIdCard.getText().toString());
                            }
                        }).show();
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                String filePath = data.getStringExtra(CameraActivity.KEY_OUTPUT_FILE_PATH);
                if (!TextUtils.isEmpty(contentType)) {
                    ProgressDialogUtil.startProgressDialog(this);
                    if (AppUtils.getAppName(this).equals(getResources().getString(R.string.ssq_app_name))) {
                        if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                        } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                        }
                    } else {
                        ocrIdCard(filePath);
                    }
                }
            }
        }
    }


    /**
     * 获取身份正反面信息
     *
     * @param idCardSide 正反面
     * @param filePath   文件地址
     */
    private void recIDCard(final String idCardSide, final String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);

        OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                ProgressDialogUtil.stopProgressDialog();
                if (result != null) {
                    if (result.getDirection() == 0) {
                        tvTip.setText("边框完整、字迹清晰、亮度均衡、如有误请重拍");
                        if (idCardSide.equals(IDCardParams.ID_CARD_SIDE_FRONT)) {
                            GlideUtils.setHeadImg(ivFront, filePath);
                            tvName.setText(result.getName().getWords());
                            tvIdCard.setText(result.getIdNumber().getWords());
                            llCardFront.setVisibility(View.GONE);
                            llFrontInfo.setVisibility(View.VISIBLE);
                        } else {
                            GlideUtils.setHeadImg(ivBack, filePath);
                            tvIssueAuthority.setText((result.getIssueAuthority().getWords()));
                            tvExpiryDate.setText(String.format("%s-%s", result.getSignDate().getWords(),
                                    result.getExpiryDate().getWords()));
                            llCardBack.setVisibility(View.GONE);
                            llBackInfo.setVisibility(View.VISIBLE);
                        }
                        if (!StringUtil.isEmpty(tvName.getText().toString()) &&
                                !StringUtil.isEmpty(tvIssueAuthority.getText().toString())) {
                            btnRegister.setBackgroundResource(R.drawable.btn_blue_layout);
                            btnRegister.setClickable(true);
                        }
                    } else {
                        ToastUtils.show("识别错误，请重新拍照");
                    }
                }
            }

            @Override
            public void onError(OCRError error) {

            }
        });
    }

    public void updateInfo(String detail) {
        ProgressDialogUtil.startProgressDialog(this);
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        if (!StringUtil.isEmpty(userInfoBean.getAvatarUrl())) {
            param.put("head", userInfoBean.getAvatarUrl());
        }
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        if (!StringUtil.isEmpty(String.valueOf(userInfoBean.getHun()))) {
            param.put("hun", String.valueOf(userInfoBean.getHun()));
        }
        if (!StringUtil.isEmpty(userInfoBean.getEdu())) {
            param.put("edu", userInfoBean.getEdu());
        }
        if (!StringUtil.isEmpty(userInfoBean.getZy())) {
            param.put("zy", userInfoBean.getZy());
        }
        if (!StringUtil.isEmpty(userInfoBean.getAdress())) {
            param.put("adress", userInfoBean.getAdress());
        }
        if (!StringUtil.isEmpty(userInfoBean.getShouru())) {
            param.put("shouru", userInfoBean.getShouru());
        }
        if (!StringUtil.isEmpty(userInfoBean.getZichan())) {
            param.put("zichan", userInfoBean.getZichan());
        }
        param.put("sfz", tvIdCard.getText().toString());
        param.put("name", tvName.getText().toString());
        if (!StringUtil.isEmpty(userInfoBean.getAihao())) {
            param.put("aihao", userInfoBean.getAihao());
        }
        param.put("detail", detail);
        HttpUtil.getInstance().postDataAsynToNet(UPDATE, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                ProgressDialogUtil.stopProgressDialog();
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum == 0) {
                    SPUtil.put("userInfo", baseBean.data);
                    if (!getIntent().getBooleanExtra("isBlack", false)) {
                        startActivity(new Intent(CardActivity.this, BankActivity.class));
                    }
                    finish();
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                LogUtils.d(" ************** updateInfo  failed ");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ProgressDialogUtil.stopProgressDialog();
    }


    @Override
    public void onDetectFinish(String token, int errorCode, String errorMessage, String data) {
        LogUtil.w("onDetectFinish", errorCode + "        " + errorMessage);
        if (errorCode == 1000) {
            verify(token, data.getBytes());
        } else {
            ToastUtils.show("认证失败，请重新认证");
            ProgressDialogUtil.stopProgressDialog();
        }
    }

    @Override
    public void onPreStart() {

    }

    @Override
    public void onPreFinish(String token, int errorCode, String errorMessage) {
        LogUtil.i(token + "  onPreFinish  " + errorCode);
        if (errorCode == 1000) {
            megLiveManager.setVerticalDetectionType(MegLiveManager.DETECT_VERITICAL_FRONT);
            megLiveManager.startDetect(this);
        }
    }

    // ----------------  旷视 ---------------------

    private void getBizToken(String idcardName, String idcardNum) {
        ProgressDialogUtil.startProgressDialog(this);
        Map<String, String> param = new HashMap<>();
        param.put("sign", sign);
        param.put("sign_version", SIGN_VERSION);
        param.put("liveness_type", "meglive");
        param.put("comparison_type", "1");
        param.put("idcard_name", idcardName);
        param.put("idcard_number", idcardNum);
        HttpUtil.getInstance().postDataAsynToNet(GET_BIZTOKEN_URL, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) {
                LogUtil.i(jsonString + " ********** ");
                JSONObject jsonObject = JSON.parseObject(jsonString);

                megLiveManager.preDetect(CardActivity.this, jsonObject.getString("biz_token"), "en", "https://api.megvii.com", CardActivity.this);
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }


    private void verify(String token, byte[] data) {
        Map<String, Object> params = new HashMap<>();
        params.put("sign", sign);
        params.put("sign_version", SIGN_VERSION);
        params.put("biz_token", token);
        params.put("meglive_data", data);
        HttpUtil2.getInstance().postDataAsynToNet(VERIFY_URL, params, new HttpUtil2.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                ProgressDialogUtil.stopProgressDialog();
                JSONObject jsonObject = JSON.parseObject(jsonString);
                LogUtil.i(jsonString + " **********  ");
                if (jsonObject.getInteger("result_code") == 2000) {
                    IdCardAndBankInfo idCardAndBankInfo = new IdCardAndBankInfo();
                    idCardAndBankInfo.setQfjg(tvIssueAuthority.getText().toString());
                    idCardAndBankInfo.setYxq(tvExpiryDate.getText().toString());
                    idCardAndBankInfo.setFlag("1");
                    updateInfo(JSON.toJSONString(idCardAndBankInfo));
                } else {
                    ToastUtils.show("不是本人");
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                LogUtil.i("失败*****************  ");
            }
        });

    }


    /**
     * 旷视 身份认证
     *
     * @param filePath
     */
    private void ocrIdCard(final String filePath) {
        Map<String, Object> params = new HashMap<>();
        params.put("api_key", Constants.FACE_ID_API_KEY);
        params.put("api_secret", Constants.FACE_ID_SECRET);
        params.put("image", new File(filePath));
        HttpUtil2.getInstance().postDataAsynToNet(OCR_ID_CARD, params, new HttpUtil2.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                ProgressDialogUtil.stopProgressDialog();
                JSONObject jsonObject = JSON.parseObject(jsonString);
                if (jsonObject.containsKey("error")) {
                    ToastUtils.show("请拍摄正确的身份证照片");
                } else {
                    if (jsonObject.getInteger("result") == 1001 || jsonObject.getInteger("result") == 1002) {
                        if (jsonObject.getInteger("side") == 0) {
                            GlideUtils.setHeadImg(ivFront, filePath);
                            tvName.setText(jsonObject.getJSONObject("name").getString("result"));
                            tvIdCard.setText(jsonObject.getJSONObject("idcard_number").getString("result"));
                            llCardFront.setVisibility(View.GONE);
                            llFrontInfo.setVisibility(View.VISIBLE);
                        } else if (jsonObject.getInteger("side") == 1) {
                            GlideUtils.setHeadImg(ivBack, filePath);
                            tvIssueAuthority.setText(jsonObject.getJSONObject("issued_by").getString("result"));
                            tvExpiryDate.setText(String.format("%s-%s",
                                    jsonObject.getJSONObject("valid_date_start").getString("result"),
                                    jsonObject.getJSONObject("valid_date_end").getString("result")));
                            llCardBack.setVisibility(View.GONE);
                            llBackInfo.setVisibility(View.VISIBLE);
                        }
                        if (!StringUtil.isEmpty(tvName.getText().toString()) &&
                                !StringUtil.isEmpty(tvIssueAuthority.getText().toString())) {
                            btnRegister.setBackgroundResource(R.drawable.btn_blue_layout);
                            btnRegister.setClickable(true);
                        }
                    } else {
                        ToastUtils.show("请拍摄清楚的身份证照片");
                    }
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                LogUtil.i("失败");
            }
        });

    }


    /**
     * 设置用户协议
     */
    public void setAgreement() {
        SpannableStringBuilder spannable;
        String content;

        content = "登录即同意《用户授权及承诺书》";
        spannable = new SpannableStringBuilder(content);
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                StatisticsUtils.intentWebView(CardActivity.this,
                        Constants.SSQ_CNS_HTML, getResources().getString(R.string.xys), "");
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }

        }, 5, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        ForegroundColorSpan span1 = new ForegroundColorSpan(getResources().getColor(R.color.color_4E77FF));
        spannable.setSpan(span1, 5, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvUserAgreement.setHighlightColor(Color.TRANSPARENT);//去掉点击后的背景颜色为透明
        tvUserAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        tvUserAgreement.setText(spannable);
    }

}
